package com.atgouwu.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atgouwu.mall.common.utils.HttpUtils;
import com.atgouwu.mall.member.dao.MemberLevelDao;
import com.atgouwu.mall.member.entity.MemberLevelEntity;
import com.atgouwu.mall.member.exception.PhoneException;
import com.atgouwu.mall.member.exception.UsernameException;
import com.atgouwu.mall.member.vo.MemberUserLoginVo;
import com.atgouwu.mall.member.vo.MemberUserRegisterVo;
import com.atgouwu.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atgouwu.mall.common.utils.PageUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.atgouwu.mall.member.dao.MemberDao;
import com.atgouwu.mall.member.entity.MemberEntity;
import com.atgouwu.mall.member.service.MemberService;

import javax.annotation.Resource;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Page<>(Long.valueOf(String.valueOf(params.get("page"))), Long.valueOf(String.valueOf(params.get("size")))),
                new QueryWrapper<MemberEntity>()
        );
        return new PageUtils(page.getRecords(), (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    //提交注册
    @Override
    public void register(MemberUserRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel(); //获取默认等级
        memberEntity.setLevelId(levelEntity != null ? levelEntity.getId() : 1L); //默认等级
        checkPhoneUnique(vo.getPhone()); //检查手机号是否唯一(感知异常,异常机制)
        checkUserNameUnique(vo.getUserName()); //检查用户名是否唯一
        memberEntity.setNickname(vo.getUserName()); //昵称
        memberEntity.setUsername(vo.getUserName()); //用户名
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); //密码MD5加密
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode); //密码
        memberEntity.setMobile(vo.getPhone()); //手机号
        memberEntity.setGender(0); //性别
        memberEntity.setCreateTime(new Date()); //插入时间
        baseMapper.insert(memberEntity); //保存到数据库
    }

    //检查手机号是否唯一
    //@Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer phoneCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (phoneCount > 0) {
            throw new PhoneException();
        }
    }

    //检查用户名是否唯一
    //@Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer usernameCount = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    //账号密码登录
    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct)); //去数据库查
        if (memberEntity != null) { //账号存在
            String passwords = memberEntity.getPassword(); //数据库密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwords); //密码匹配
            if (matches) { //登录成功
                return memberEntity;
            }
        }
        return null;
    }

    //微博登录注册
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) { //已注册过
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in() + "");
            baseMapper.updateById(update); //更新用户access_token,令牌过期时间
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in() + "");
            return memberEntity;
        } else { //没有查到当前社交用户,需注册
            MemberEntity register = new MemberEntity();
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query); //查询微博当前社交用户的社交账号信息(昵称,性别等)
            if (response.getStatusLine().getStatusCode() == 200) { //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");
                register.setNickname(name);
                register.setGender("m".equals(gender) ? 1 : 0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(socialUser.getUid());
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(socialUser.getExpires_in() + "");
                baseMapper.insert(register); //把用户信息插入数据库
            }
            return register;
        }
    }

}